function getDate() {
  let data = new Date();
  let dataStr = data.Format('yyyy年MM月DD日 hh时mm分ss秒');
  $('#date_show').text(dataStr);
}

// 退出登录
function logout() {
  $.get("action.php?a=logout", function (res) {
    if (res.success) {
      window.location = 'login.html'
    } else {
      layer.msg(res.message);
    }
  });
}

// 提交答题试卷
function complete() {
  // 弹框显示
  let loading = layer.msg("正在提交试卷，请稍等一下！", {
    icon: 16,
    shade: 0.3,
    time: 0
  });
  // 题目数量
  let count = $('.title_header').length;
  // 提交数据
  let postdata = `count=${count}&answers=`;
  $('.title_header').each((i, item) => {
    let id = $(item).data('id');
    let temp = '';
    // 将答题数据合并到变量里
    $(item).find('.answer_select').each((j, ite) => {
      temp += $(ite).data('val');
    });
    postdata += id + "_" + temp + ',';
  });
  // 构造要发送的post数据
  postdata = postdata.substr(0, postdata.length - 1);


  // 提交数据到后台php文件里
  $.ajax({
    url: "action.php?a=commit",
    method: 'post',
    data: postdata,
    success: function (data) {
      layer.close(loading);
      // 提交数据异常或后台处理出错
      if (!data.success) {
        layer.msg(data.message)
      } else {
        // 关闭弹窗
        layer.closeAll();
        let jobj = JSON.parse(data.data);
        //自定页
        layer.open({
          type: 1,
          skin: 'layui-layer-rim', //加上边框
          area: ['420px', '240px'], //宽高
          content: `<div class="finalPop">
          <p>答对题目数：${jobj.rightNum}</p>
          <p>最终分数：${jobj.score}</p>
      </div>`,
          cancel: function (index, layero) {
            if (confirm('确定要关闭么')) { //只有当点击confirm框的确定时，该层才会关闭
              layer.close(index)
              logout();
            }
            return false;
          }
        });
      } // 成功
    }
  });


  setTimeout(function () {
    layer.close(loading);
  }, 3000);
}

$(() => {
  // 更新时间
  getDate();
  setInterval(getDate, 1000);

  let tempMinute;
  let timer;

  layer.confirm('确定开始考试吗？', {
    btn: ['确定'] //按钮
  }, function (index) {
    tempMinute = $('#retainTime').data('time');
    timer = setInterval(() => {
      // let curDate = new Date();
      // let rDate = curDate.getTime() - tempDate.getTime();
      // let rMin = rDate/ 1000;

      if (tempMinute == 3) {
        layer.msg("还有3分钟自动交卷！");
      }

      if (tempMinute == 1) {
        clearInterval(timer);
        complete();
      }

      // console.log(tempMinute)
      $('#retainTime').text(`剩余时间：${--tempMinute}分钟`);
    }, 60 * 1000);
    layer.close(index);
  });


  // 选中特效
  $('.answers p').on('click', (e) => {
    let val = e.target.dataset.val;
    let ans = val;
    let obj = $(e.target).parent().parent();
    // console.log(val, type, id, ans);

    let index = obj.data('index');
    let id = obj.data('id');
    let type = obj.data('type');
    $(`.p_point:eq(${index - 1})`).addClass('g');

    console.trace(e.target);

    if ('radio' === type || 'judge' === type) {
      $(e.target).addClass("answer_select").siblings().removeClass("answer_select").parent().next().text('您的选择是：' + ans);
    } else if ('checkbox' === type) {
      let elect = $(e.target).attr('class') === 'answer_select';
      if (elect) {
        $(e.target).removeClass("answer_select")
      } else {
        $(e.target).addClass("answer_select")
      }
      // let anss = $(e.target).siblings().attr("answer_select");
      // .removeClass("answer_select").parent().next().text('您的选择是：' + ans);
    }
  });


  // 结束答题
  $('#ok').on('click', (e) => {
    let total = $(`.p_point`).length;
    let selNum = 0;
    $(`.p_point`).each((i, item) => {
      if ($(item).eq(0).attr('class').indexOf('g') > 0) {
        selNum++;
      }
    });
    // 未答完题目提示
    if (selNum < total) {
      layer.confirm('您还有题目未答完，是否提交？', {
        btn: ['冲啊', '缓缓'] //按钮
      }, function () {
        complete();

      }, function () {
        layer.msg('继续奥里给！');
      });
    };
    if (selNum == total) {
      complete();
    }
  });

  // 取消答题
  $('#cancel').on('click', (e) => {
    layer.confirm('返回登录页面', {
      btn: ['确定', '取消'] //按钮
    }, function () {
      logout();
    }, function () {
      layer.msg('还可以继续答题');
    });
  });
});